package org.tiangou.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.tiangou.entity.User;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class MainTest01 {
    private static final String CHARSET = "UTF-8" ;
    private static final String KEY = "112233abc" ;


    public static void create() throws Exception {
        // 1.Header
        JSONObject originHeader = new JSONObject();
        originHeader.put("typ","JWT");
        originHeader.put("alg","HS256") ;
        String header = Base64
                .encodeBase64URLSafeString(originHeader.toJSONString().getBytes(CHARSET));

        // 2.Payload
        JSONObject originPayload = new JSONObject();
        User user = new User("zing","null","男",18) ;
        originPayload.put("user",user);
        String payload = Base64
                .encodeBase64URLSafeString(originPayload.toJSONString().getBytes(CHARSET));

        // 3.signature
        String signature = hmacSha256Encode(header, payload);
        String token = String.format("%s.%s.%s",header,payload,signature) ;


        System.out.println(token);
    }

    private static String hmacSha256Encode(String header,String payload) throws Exception {
        // 获取某个摘要算法对象
        Mac hmacSHA256 = Mac.getInstance("HmacSHA256") ;

        // 指定摘要算法的key
        SecretKeySpec key = new SecretKeySpec(KEY.getBytes(CHARSET), "HmacSHA256");
        hmacSHA256.init(key);

        hmacSHA256.update(header.getBytes(CHARSET));
        hmacSHA256.update(".".getBytes(CHARSET));
        hmacSHA256.update(payload.getBytes(CHARSET));
        byte[] bytes = hmacSHA256.doFinal(payload.getBytes(CHARSET));
        return Base64.encodeBase64URLSafeString(bytes) ;
    }


    public static void main(String[] args) throws Exception {
        create() ;
    }
}
